package com.xuecheng.media.application.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.base.model.RestResponse;
import com.xuecheng.media.application.service.MediaFilesApplication;
import com.xuecheng.media.application.vo.req.MediaFilesPageQry;
import com.xuecheng.media.application.vo.resp.FileUploadResultDto;
import com.xuecheng.media.application.vo.resp.MediaFilesDto;
import com.xuecheng.media.domain.model.ChunkMergeDo;
import com.xuecheng.media.domain.model.ChunkUploadDo;
import com.xuecheng.media.domain.model.FileUploadDo;
import com.xuecheng.media.domain.model.entity.MediaFiles;
import com.xuecheng.media.domain.service.MediaFilesService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Objects;

/**
 * @Author: LiJunXi
 * @Description:
 * @Date: 2024-08-04  13:44
 */
@Service
public class MediaFilesApplicationImpl implements MediaFilesApplication {

    @Autowired
    private MediaFilesService mediaFilesService;

    @Override
    public FileUploadResultDto uploadFile(MultipartFile multipartFile, Long companyId, String objectName) {
        FileUploadDo fileUploadDo = FileUploadDo.getDefaultFile(
                multipartFile.getSize(), multipartFile.getOriginalFilename()
        );
        String absolutePath = null;
        File tempFile;
        try {
            // 创建临时文件夹
            tempFile = File.createTempFile("minio", "tmp");
            multipartFile.transferTo(tempFile);
            absolutePath = tempFile.getAbsolutePath();
        } catch (IOException e){
            throw new XueChengPlusException("上传图片出错");
        }

        MediaFiles mediaFiles = mediaFilesService.uploadFile(fileUploadDo, absolutePath, companyId, objectName);
        tempFile.deleteOnExit();

        return new FileUploadResultDto(mediaFiles.getUrl());
    }

    @Override
    public RestResponse<Boolean> checkFile(String fileMd5) {
        MediaFiles mediaFiles = mediaFilesService.getById(fileMd5);
        Boolean res = false;
        if (Objects.nonNull(mediaFiles)){
            res = mediaFilesService.checkMinioFileExit(mediaFiles);
        }
        return RestResponse.success(res);
    }

    @Override
    public RestResponse<Boolean> checkChunk(String fileMd5, Integer chunk) {
        return RestResponse.success(mediaFilesService.checkChunkExit(fileMd5, chunk));
    }

    @Override
    public RestResponse<Void> uploadChunk(MultipartFile file, String fileMd5, int chunk) {
        if (Objects.isNull(file) || Objects.isNull(fileMd5) || chunk < 0){
            throw new XueChengPlusException("请求参数有误");
        }
        String absolutePath;
        File tempFile;
        try {
            // 创建临时文件
            tempFile = File.createTempFile("minio", "tmp");
            file.transferTo(tempFile);
            absolutePath = tempFile.getAbsolutePath();
        } catch (IOException e){
            throw new XueChengPlusException("创建临时文件出错");
        }

        mediaFilesService.uploadChunk(new ChunkUploadDo(fileMd5, chunk, absolutePath));
        tempFile.deleteOnExit();
        return RestResponse.success();
    }

    @Override
    public RestResponse<Void> mergeChunks(String fileMd5, Integer chunkTotal, String filName, Long companyId) {
        if (Objects.isNull(fileMd5) || Objects.isNull(chunkTotal) || Objects.isNull(filName) || Objects.isNull(companyId)){
            throw new XueChengPlusException("请求参数有误");
        }

        mediaFilesService.mergeChunks(new ChunkMergeDo(fileMd5, chunkTotal, filName, companyId));
        return RestResponse.success();
    }

    @Override
    public PageResult<MediaFilesDto> mediaFilesPage(PageParams pageParams, MediaFilesPageQry mediaFilesPageQry) {
        //构建查询条件对象
        LambdaQueryWrapper<MediaFiles> queryWrapper = new LambdaQueryWrapper<>();
        //构建查询条件，根据课程名称查询
        queryWrapper.eq(StringUtils.isNotEmpty(mediaFilesPageQry.getFileType()), MediaFiles::getFileType, mediaFilesPageQry.getFileType());
        //构建查询条件，根据课程审核状态查询
        queryWrapper.like(StringUtils.isNotEmpty(mediaFilesPageQry.getFilename()), MediaFiles::getFilename, mediaFilesPageQry.getFilename());
        PageResult<MediaFiles> result = mediaFilesService.queryCourseBasePage(queryWrapper,
                new Page<>(pageParams.getPageNo(), pageParams.getPageSize()));

        return new PageResult<>(BeanUtil.copyToList(result.getItems(), MediaFilesDto.class),
                result.getCounts(), result.getPage(), result.getPageSize());
    }

    @Override
    public MediaFiles getMediaFiesById(String mediaId) {
        if (Objects.isNull(mediaId)){
            throw new XueChengPlusException("媒资ID参数不能为空");
        }
        MediaFiles mediaFiles = mediaFilesService.getById(mediaId);
        if (Objects.isNull(mediaFiles)){
            throw new XueChengPlusException("媒资不存在");
        }

        return mediaFiles;
    }
}
